<template>
    <div>
        <div class="mark-header">
            <ComTitle :list="titles"></ComTitle>
            <div class="mark-link-container">
                <SCButton type="primary" @click="toPreMarkPage">管理预标注文件</SCButton>
                <SCButton type="primary" @click="toArtificialMarkPage">管理人工标注文件</SCButton>
            </div>
        </div>

        <div class="multiple-btns">
            <div class="level-container">
                <SCButton
                    class="level-button"
                    :disabled="state.fileStack.length <= 1 || tableLoading"
                    @click="handleBack"
                >
                    <SCIcon>
                        <ArrowLeft />
                    </SCIcon>
                </SCButton>
                <div class="level-desc">{{ name }} {{ filePath ? "/ " + filePath : "" }}</div>
            </div>
        </div>

        <div class="table-container" v-loading="listLoading">
            <SCTable style="width: 100%" :data="fileDatasource" :stripe="false">
                <SCTableColumn prop="name" label="名称" :min-width="250">
                    <!-- <template #default="scope">
                        <FileDisplay :isCatalog="scope.row.type === 2">
                            <span>
                                <SCLink
                                    @click="toCatalogDetail(scope.row)"
                                    v-if="scope.row.type === 2"
                                    >{{ scope.row.name }}</SCLink
                                >
                                <span v-else>{{ scope.row.name }}</span>
                            </span>
                        </FileDisplay>
                    </template> -->
                    <template v-slot="{ row }">
                        <div
                            v-if="row.type === 2"
                            class="file-name folder"
                            @click="openFolder(row)"
                        >
                            <!-- 文件夹 -->
                            <svg-icon icon-class="folder" />
                            {{ row.name }}
                        </div>
                        <div class="file-name" v-else>
                            <svg-icon icon-class="file_done" />
                            {{ row.name }}
                        </div>
                    </template>
                </SCTableColumn>
                <SCTableColumn prop="preMarkStatus" label="是否完成了预标注" :min-width="130">
                    <template #default="scope">
                        <SCSwitch
                            v-model="scope.row.preMarkStatus"
                            active-color="#A446CA"
                            inactive-color="rgba(0, 0, 0, 0.12)"
                            :active-value="1"
                            :inactive-value="2"
                            @change="changeFilePreMarkStatus(scope.row)"
                        />
                    </template>
                </SCTableColumn>
                <SCTableColumn prop="needMarkStatus" label="是否需要人工标注" :min-width="130">
                    <template #default="scope">
                        <SCSwitch
                            v-model="scope.row.needMarkStatus"
                            active-color="#A446CA"
                            inactive-color="rgba(0, 0, 0, 0.12)"
                            :active-value="1"
                            :inactive-value="2"
                            @change="changeNeedFileMarkStatus(scope.row)"
                        />
                    </template>
                </SCTableColumn>
                <SCTableColumn prop="size" label="数据大小" :min-width="80"> </SCTableColumn>
                <SCTableColumn prop="updateTime" label="最后修改时间" :min-width="160">
                </SCTableColumn>
                <SCTableColumn label="操作" fixed="right" :min-width="100">
                    <template #default="scope">
                        <div class="action-btn" v-if="scope.row.type !== 2">
                            <SCButton
                                @click="mark(scope.row)"
                                size="small"
                                type="primary"
                                :loading="scope.row.markLoading"
                                >标注</SCButton
                            >
                        </div>
                    </template>
                </SCTableColumn>
            </SCTable>

            <div class="pagination-container">
                <SCPagination
                    class="pagination"
                    v-model:current-page="pageQuery.currentPage"
                    v-model:page-size="pageQuery.pageSize"
                    :total="pageQuery.total"
                    :page-sizes="[10, 20, 50]"
                    layout="prev,pager,next,sizes,jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
            <!-- <input type="file" webkitdirectory directory ref="fileRef" @change="changeFile" /> -->

            <PathSelectDialog
                :visible="pathSelectVisible"
                @hideDialog="hidePathDialog"
                @updateStorePath="updateStorePath"
            />
        </div>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ArrowLeft } from "@element-plus/icons-vue";
import {
    getMarktaskFileList,
    updateFileMarkStatus,
    updateFilePreMarkStatus,
} from "~/api/dataset.ts";
import { markFile, getHeart, submitDownloadFile, MasktaskItem } from "~/api/mark.ts";
import ComTitle from "~/components/ComTitle.vue";
import FileDisplay from "~/components/FileDisplay.vue";
import { SCMessage } from "@sribd/sc-ui";
import PathSelectDialog from "./PathSelectDialog.vue";

const route = useRoute();
const router = useRouter();
const dataSetId = +(route.params?.id || "0");
const name = route.params?.name;
const parentIds = typeof route.params.parent === "string" ? route.params.parent.split(",") : [];
const taskId = +(route.query?.taskId || "0");
const fileRef = ref();
const titles = [
    {
        name: "数据管理",
        routeName: "dataIndex",
        params: {
            curTab: "mark",
        },
    },
    {
        name: "数据标注",
    },
];
const listLoading = ref(false);
const filePath = ref("");
const pageQuery = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});
const fileDatasource = ref([]);
const pathSelectVisible = ref(false);
const selectedRow = ref<MasktaskItem & { maskLoading: boolean }>();
interface State {
    fileStack: Array<{ id: number; name?: string }>;
}
const state = reactive<State>({
    fileStack: [{ id: 0 }],
});
watch(
    () => state.fileStack,
    () => {
        filePath.value = state.fileStack
            .slice(1)
            .map((item) => item.name)
            .join("/");
        console.log(filePath.value);
    },
    { deep: true },
);

const hidePathDialog = () => {
    pathSelectVisible.value = false;
};
const handleBack = () => {
    const upperId = state.fileStack[state.fileStack.length - 2].id;
    search(upperId, 2);
};
let currentFolder: { id: number } | null;
const openFolder = (folder) => {
    pageQuery.currentPage = 1;
    currentFolder = folder;
    search(folder.id, 1);
};
const updateStorePath = async (path: string) => {
    try {
        if (!selectedRow) {
            return;
        }
        selectedRow.maskLoading = true;
        const fileUrls = await markFile(selectedRow.value.id, taskId);
        await submitDownloadFile({
            storeDir: path,
            openSnap: true,
            fileUrls,
        });
        SCMessage({
            message: "标注文件成功！",
            type: "success",
        });
    } catch (e) {
        SCMessage({
            message: e.msg || "标注文件获取失败！",
            type: "error",
        });
    } finally {
        if (selectedRow) {
            selectedRow.maskLoading = true;
        }
    }
};

const mark = async (row: any) => {
    row.markLoading = true;
    try {
        const res = await getHeart(); // 心跳检测
        selectedRow.value = row;
        pathSelectVisible.value = true; // 路径选择弹窗
    } catch (e) {
        // 没有插件就安装插件
        router.push({
            name: "download",
        });
    } finally {
        row.markLoading = false;
    }
};
const toCatalogDetail = (row: any) => {
    const parentIds =
        typeof route.params.parentId === "string" ? route.params.parentId.split(",") : [];
    parentIds.push(row.id);
    router.push({
        name: "markTaskDetail",
        params: {
            id: dataSetId,
            name,
            parentId: parentIds.join(","),
        },
        query: {
            taskId,
        },
    });
};
// 回到上一级
const backToParent = () => {
    router.back();
};

const handleSizeChange = (size) => {
    pageQuery.currentPage = 1;
    pageQuery.pageSize = size;
    search(state.fileStack.length ? state.fileStack[state.fileStack.length - 1].id : 0);
};

const handleCurrentChange = (page) => {
    pageQuery.currentPage = page;
    search(state.fileStack.length ? state.fileStack[state.fileStack.length - 1].id : 0);
};
const search = async (parentId, type = 3) => {
    listLoading.value = true;
    try {
        const params: any = {
            page: pageQuery.currentPage,
            pageSize: pageQuery.pageSize,
            id: taskId,
        };
        // const parentId = route.params.parentId;
        if (parentId) {
            params.parentId = +parentId;
        }
        const { total, list, filePath: path } = await getMarktaskFileList(params);
        fileDatasource.value = list;
        pageQuery.total = total || 0;
        changeFileIdStack(type);
        if (+parentId === 0) {
            state.fileStack = [{ id: 0 }];
        }
    } catch (e) {
        SCMessage({
            message: e.msg || "获取标注文件列表失败!",
            type: "error",
        });
    } finally {
        listLoading.value = false;
    }
};
const toPreMarkPage = () => {
    const { id, name, parentId } = route.params;
    router.push({
        name: "preMarkPage",
        params: {
            id,
            name,
            parentId,
        },
        query: {
            taskId,
        },
    });
};
const toArtificialMarkPage = () => {
    const { id, name, parentId } = route.params;
    router.push({
        name: "artificialMarkPage",
        params: {
            id,
            name,
            parentId,
        },
        query: {
            taskId,
        },
    });
};

/**
 * type 文件路径堆栈变化标识
 * 1-打开子文件， push
 * 2-回退，pop
 * 3-其他，堆栈不变
 */
const changeFileIdStack = (type = 3) => {
    switch (type) {
        case 1:
            if (
                currentFolder &&
                state.fileStack[state.fileStack.length - 1].id !== currentFolder.id
            ) {
                state.fileStack.push(currentFolder);
            }
            break;
        case 2:
            state.fileStack.pop();
            currentFolder = state.fileStack[state.fileStack.length - 1];
            break;
        default:
            break;
    }
};
search(route.params.parentId);

const changeFilePreMarkStatus = async (row: any) => {
    const { id, preMarkStatus } = row;
    row.preMarkLoading = true;
    try {
        await updateFilePreMarkStatus({
            id,
            preMarkStatus,
            taskId,
        });

        search(currentFolder?.id);
    } catch (e) {
        SCMessage({
            message: e.msg || "是否完成了预标注状态设置失败!",
            type: "error",
        });
    } finally {
        row.preMarkLoading = false;
    }
};
const changeNeedFileMarkStatus = async (row: any) => {
    const { id, needMarkStatus } = row;
    row.needMarkLoading = true;
    try {
        await updateFileMarkStatus({
            id,
            needMarkStatus,
            taskId,
        });
    } catch (e) {
        SCMessage({
            message: e.msg || "是否需要人工标注状态设置失败!",
        });
    } finally {
        row.needMarkLoading = false;
    }
};
</script>
<style lang="scss" scoped>
.multiple-btns {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    :deep(.sc-button) {
        border-radius: 2px;
        min-width: 72px;
    }
    .level-container {
        display: flex;
        flex: 1;
        align-items: center;
        :deep(.level-button) {
            margin-right: 8px;
            min-width: 32px;
            width: 32px;
            padding: 0;
            .sc-icon {
                margin-right: 0;
            }
        }
    }
    .level-desc {
        background: #eef3ff;
        border-radius: 4px;
        height: 32px;
        box-sizing: border-box;
        padding: 0 14px;
        color: rgba(27, 24, 27, 0.7);
        font-size: 12px;
        line-height: 32px;
        flex: 1;
    }
}
.pagination-container {
    overflow: hidden;
    margin-top: 10px;
    :deep(.pagination) {
        float: right;
    }
    :deep(.el-input__wrapper) {
        padding: 1px 8px;
    }
}

.dir-selector {
    opacity: 0;
}
.mark-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
:deep(.common-title-box) {
    margin-bottom: 0;
}
:deep(.upload-label-button) {
    display: inline;
}
.action-btn {
    :deep(.el-button) {
        margin-right: 10px;
    }
}
</style>
